<template>
  <VPivottableUi :data="curData" :cols="curCols" :vals="curVals" v-bind="$attrs" :actualVals='actualVals' :multiple="multiple" @update:vals="onUpdateVals" @change="onChange"></VPivottableUi>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import VPivottableUi from './VPivottableUi.vue';

const emit = defineEmits(['change']);

const props = defineProps({
  cols: {
    type: Array,
    default: () => [],
  },
  data: {
    type: Array,
    default: () => [],
  },
  vals: {
    type: Array,
    default: () => [],
  },
  multiple: {
    type: Boolean,
    default: true,
  }
});

const vue = getCurrentInstance().proxy;
const actualVals = ref(props.vals);

const curCols = ref([...props.cols]);
const curVals = ref([...props.vals]);
const curData = ref([...props.data]);

onMounted(() => {
  if (props.multiple) {
    if (!props.cols.includes('srfname')) {
      curCols.value = [...props.cols, 'srfname'];
    }
    if (props.vals.length) {
      const result = [...actualVals.value];
      result[0] = 'srfvalue';
      curVals.value = result;
    }
  }
  curData.value = calcData();
  vue.$forceUpdate();
});

const calcData = () => {
  if (props.multiple) {
    const result = [];
    const val = actualVals.value[0] || '';
    props.data.forEach((item) => {
      val.split(',').forEach((v) => { 
        result.push({
          ...item,
          srfname: v,
          srfvalue: item[v],
        });
      });
    });
    return result;
  }
  return props.data;
}

const refresh = () => {
  curData.value = calcData();
}

const onUpdateVals = (vals) => {
  actualVals.value = vals;
  if (vals.length) {
      const result = [...vals];
      result[0] = 'srfvalue';
      curVals.value = result;
  }
  refresh();
}

const onChange = (data) => {
  curCols.value = [...data.cols, 'srfname']
  emit('change', data);
  refresh();
}

defineExpose({
  refresh,
})

</script>
